package com.cetsk.android.talkorigins;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.util.Log;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.widget.ShareActionProvider;

import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class ClaimViewActivity extends SherlockActivity {
	WebView webview;

	private ProgressDialog dialog;

	boolean isFav = false;
	String html = null;
	MenuItem favoriteButton = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		dialog = ProgressDialog.show(this, "Loading", "Loading claim...", true);
		final Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		Log.d("LOAD_CLAIM",claim.toString());
		new Thread() {
			public void run() {
				try {
					setTitle(claim.getName());
					HTMLParse hp = new HTMLParse(getApplicationContext());
					html = hp.getClaimContent(claim);
					hp.close();
				} catch (Exception e) {
					Log.e(ClaimViewActivity.class.getName(), "HTTP Error", e);
					e.printStackTrace();
				}

				handler.sendEmptyMessage(0);
			}
		}.start();

		super.onCreate(savedInstanceState);
	}

	public void toggleFavorite(Claim claim, DatabaseHelper dbh) {
		isFav = !isFav;
		try {
			if (favRecordExists(claim, dbh)) {
				deleteFavRecord(claim, dbh);
			} else {
				insertFavRecord(claim, dbh);
			}
		} catch (SQLException sqle) {
			Log.e("SQLError", sqle.getMessage());
		} finally {
			dbh.close();
		}

		if (isFav) {
			favoriteButton.setIcon(getResources().getDrawable(R.drawable.ic_menu_star_selected));
			favoriteButton.setTitle(getString(R.string.remove_favorite));
			Toast.makeText(getApplicationContext(), R.string.add_favorite_action, Toast.LENGTH_SHORT).show();
		} else {
			favoriteButton.setIcon(getResources().getDrawable(R.drawable.ic_menu_star));
			favoriteButton.setTitle(getString(R.string.add_favorite));
			Toast.makeText(getApplicationContext(), R.string.remove_favorite_action, Toast.LENGTH_SHORT).show();
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			setContentView(R.layout.claim_view);
			webview = (WebView) findViewById(R.id.webview);
			webview.setWebViewClient(new WebViewClient() {
				// Dismisses the loading dialog after the webview loads
				public void onPageFinished(WebView view, String url) {
					try {
						dialog.dismiss();
					} catch (Exception e){
						// Doing this triggers and exception on orientation change. Not sure why
					}
				}

				// Will force any hyperlinks clicked in webview to prompt via
				// intent
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					startActivity(browserIntent);
					return true;
				}
			});
			if (html != null && html.length() > 0) {
				webview.loadData(html, "text/html", "utf-8");
			} else {
				Toast.makeText(getApplicationContext(), R.string.load_error, Toast.LENGTH_SHORT).show();
				Log.i("HTML_ERROR", "Could not Parse");
				dialog.dismiss();
				finish();
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.layout.claim_menu, menu);
		favoriteButton = (MenuItem) menu.findItem(R.id.favorite);
		
		ShareActionProvider mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
		mShareActionProvider.setShareIntent(getDefaultShareIntent());
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		DatabaseHelper dbh = new DatabaseHelper(this);
		if (favRecordExists(claim, dbh)) {
			isFav = true;
			favoriteButton.setIcon(getResources().getDrawable(R.drawable.ic_menu_star_selected));
			favoriteButton.setTitle(getString(R.string.remove_favorite));
		}
		return true;
	}
	
	public Intent getDefaultShareIntent(){
	    Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		String url = "http://www.talkorigins.org/indexcc/" + claim.getUrl();
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "TalkOrigins article: " + claim.getName());
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);

	    return shareIntent;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.favorite:
			onAddFavorite(webview);
			return true;
		case R.id.share:
			onShare(webview);
			return true;
		case R.id.url:
			onClipboard(webview);
			return true;
		case R.id.open:
			onOpen(webview);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void onAddFavorite(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		DatabaseHelper dbh = new DatabaseHelper(this);
		toggleFavorite(claim, dbh);

	}

	public void onShare(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		String url = "http://www.talkorigins.org/indexcc/" + claim.getUrl();
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "TalkOrigins article: " + claim.getName());
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);

		startActivity(Intent.createChooser(shareIntent, "Share Claim"));
	}

	public void onClipboard(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		String url = "http://www.talkorigins.org/indexcc/" + claim.getUrl();
		ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		clipboard.setText(url);
		Toast.makeText(getApplicationContext(), "URL \"" + url + "\" copied to clipboard.", Toast.LENGTH_SHORT).show();
	}

	public void onOpen(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		String url = "http://www.talkorigins.org/indexcc/" + claim.getUrl();
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		startActivity(browserIntent);
	}

	public void onViewSiblings(View v) {
		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		Intent intent = new Intent(v.getContext(), ClaimsListActivity.class);
		Claim c = new Claim();
		c.setId(claim.getParentId());
		intent.putExtra("claim", c);
		startActivity(intent);
	}

	/**
	 * Intended to return true if a fav record exists for this claim regardless
	 * of it's status
	 * 
	 * @return
	 */
	public Boolean favRecordExists(Claim claim, DatabaseHelper dbh) {

		try {
			SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement(
					"select count(*) from Favorites f where f.ClaimId = ?");
			stmt.bindLong(1, claim.getId());
			long count = stmt.simpleQueryForLong();
			dbh.close();

			if (count == 0) {
				return false;
			}
			return true;
		} catch (SQLException sqle) {
			Log.e("SQLError", sqle.getMessage());
			throw sqle;
		}
	}

	private void insertFavRecord(Claim claim, DatabaseHelper dbh) {
		SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement(
				"INSERT INTO " + DatabaseHelper.FAVORITES_TABLE + " (Id,ClaimId) VALUES (null,?)");
		stmt.bindLong(1, claim.getId());
		stmt.execute();
		stmt.close();
		dbh.close();
	}

	private void deleteFavRecord(Claim claim, DatabaseHelper dbh) {
		SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement(
				"DELETE FROM " + DatabaseHelper.FAVORITES_TABLE + " WHERE ClaimId= ?");
		stmt.bindLong(1, claim.getId());
		stmt.execute();
		stmt.close();
		dbh.close();
	}

}